from datetime import datetime 
import random
from django.core.cache import cache
from app.static import APPID, APPSERCRET, WX_LOGIN_URL, WX_GET_PHONE_URL
from app.views.annotate import (
    checkParams,
    checkLoginHandling,
)
import json
import requests
import uuid
from app.views.DBUtils import DBUtil
from ..common import HttpError, HttpSuccess, getWxAccessToken, message_cli, upload


def wxLogin(code):
    params = {
        "appid": APPID,
        "secret": APPSERCRET,
        "grant_type": "authorization_code",
        "js_code": code,
    }
    res = json.loads(requests.get(WX_LOGIN_URL, params).text)

    if res.get("errcode"):
        raise ValueError(res["errmsg"])
    return res


##用户登录
def login(request):
    json_data = json.loads(request.body)
    loginCode = json_data.get("loginCode")
    phoneCode = json_data.get("phoneCode")
    resLogin = wxLogin(loginCode)
    ##拿到用户的opneid
    openid = resLogin["openid"]
    ##去数据库里查看有没有登录记录
    select_sql = 'select id from user'
    _,userLogin = DBUtil.execute_insert_or_update(select_sql)
    ##如果没有登录,则去获取手机号，已经存在的话就直接生成token返回给前端
    if not userLogin:
        wxAccessToken = getWxAccessToken(APPID, APPSERCRET)
        res = requests.post(
            WX_GET_PHONE_URL + wxAccessToken, json={"code": phoneCode}
        ).json()
        if res.get("errcode"):
            raise ValueError(res["errmsg"])
        phone = res["phone_info"]["phoneNumber"]
        insert_sql = f"insert into user(phone,openid)values('{phone}','{openid}')"
        DBUtil.execute_insert_or_update(insert_sql)
    token = uuid.uuid4()
    cache.set(token, openid, 30 * 60 * 60 * 24)
    return HttpSuccess(data={"token": token, "openid": openid}, msg="登录成功")
    


##用户登录(自定义手机号码登录)
@checkParams(["phone", "code", "loginCode"])
def login_by_user(request):
    json_data = json.loads(request.body)
    loginCode = json_data.get("loginCode")
    phone = json_data.get("phone")
    code = json_data.get("code")
    ##验证码是否正确
    code_redis = cache.get(phone)
    if code_redis != code:
        return HttpError(msg="验证码不正确，请重新输入")
    resLogin = wxLogin(loginCode)
    ##拿到用户的opneid
    openid = resLogin["openid"]
    ##去数据库里查看有没有登录记录
    select_sql = 'select id from user'
    _,userLogin = DBUtil.execute_insert_or_update(select_sql)
    if not userLogin:
        insert_sql = f"insert into user(phone,openid)values({phone},{openid})"
        DBUtil.execute_insert_or_update(insert_sql)
    token = uuid.uuid4()
    cache.set(token, openid, 30 * 60 * 60 * 24)
    ##登录完清除验证码绑定
    cache.delete(phone)
    return HttpSuccess(data={"token": token, "openid": openid}, msg="登录成功")


##用户注销登录
@checkLoginHandling
def loginout(request):
    token = request.META.get("HTTP_X_TOKEN")
    cache.delete(token)
    return HttpSuccess(msg="注销成功")


##上传用户图片
@checkLoginHandling
def uploadImg(request):
    file = request.FILES.get("file")
    url = upload(file)
    return HttpSuccess(data={"url": url})


##更新用户信息
@checkLoginHandling
def updateUserInfo(request):
    token = request.META.get("HTTP_X_TOKEN")
    openid = cache.get(token)
    json_data = json.loads(request.body)
    sql = "update  user set "
    filter_list = []
    for index, (key,value) in enumerate(json_data.items()):
        if value:
            filter_list.append(f"""{key} = '{value}'""") 
    sql = f"""{sql}{','.join(filter_list)} where openid = '{openid}' """
    DBUtil.execute_insert_or_update(sql)
    return HttpSuccess(msg="修改成功")


##获取用户信息
@checkLoginHandling
def getUserInfo(request):
    need_get_type = False
    now_openid = cache.get(request.META.get("HTTP_X_TOKEN"))
    json_data = json.loads(request.body) if request.body else {}
    if json_data.get('openid')!= None:
        openid = json_data.get('openid')
        need_get_type = True
    else:
        openid = now_openid
    sql = f"select * from user where openid = '{openid}'"
    _,result = DBUtil.execute_select(sql)
    if len(result)==0:
        raise HttpError(msg='无该用户信息')
    if need_get_type:
       result_openid = result[0]['openid']
       select_sql = f"select fans from user where openid = '{now_openid}'" 
       _, owner = DBUtil.execute_select(select_sql)
       if len(owner)==0:
            raise HttpError(msg='无该用户信息')
       fans = json.dumps(owner[0]['fans'])
       type = 1 if result_openid in fans else 0
       result[0]['type'] = type
    return HttpSuccess(data=result[0])


def generate_random_code(length=4):
    return "".join([str(random.randint(0, 9)) for _ in range(length)])


##发送短信
@checkParams(["phone"])
def sendmessage(request):
    json_data = json.loads(request.body)
    phone = json_data.get("phone")
    cli = message_cli()
    cli.create_client()
    code = generate_random_code()
    msg = cli.send_message(phone, code)
    if msg != "发送成功":
        return HttpError(msg=msg)
    return HttpSuccess(msg=msg)

##获取用户关注，粉丝列表
@checkLoginHandling
@checkParams(["type"])
def getUserFriend(request):
    json_data = json.loads(request.body)
    type = json_data.get("type")
    token = request.META.get("HTTP_X_TOKEN")
    openid = cache.get(token)
    sql = f"select atts,fans from user where openid = '{openid}'"
    _ ,result =  DBUtil.execute_select(sql)
    if len(result) == 0:
        raise(HttpError(data = "用户不存在"))
    user_info = result[0]
    if int(type) == 0:
        data = json.loads(user_info['atts'])
    else:
        data = json.loads(user_info['fans'])
    values = None
    if len(data) ==1:
        values = f"""('{data[0]}')"""
    elif len(data) ==0:
        return HttpSuccess(data = [])
    else:
        values = tuple(data)
    sql = f"""select *,if({'atts' if(int(type)==0) else 'fans' } like '%{openid}%',1,0)  as type  from user where openid in {values}"""
    _,result = DBUtil.execute_select(sql)
    return HttpSuccess(data = result)


##关注或者取消
@checkLoginHandling
@checkParams(["type",'openid_user'])
def attention(request):
    json_data = json.loads(request.body)
    type = int(json_data.get("type"))
    openid_user = json_data.get("openid_user")
    token = request.META.get("HTTP_X_TOKEN")
    openid = cache.get(token)
    select_sql = f"select fans from user where openid = '{openid_user}'"
    select_sql_my = f"select atts from user where openid = '{openid}'"
    _ ,result_user =  DBUtil.execute_select(select_sql)
    _ ,result_user_my =  DBUtil.execute_select(select_sql_my)
    if len(result_user) ==0 or len(result_user_my) == 0:
        raise(HttpError(data = "用户不存在"))
    fans = result_user[0]['fans']
    atts = result_user_my[0]['atts']
    fans_list = json.loads(fans)
    atts_list = json.loads(atts)
    if type == 1:
        fans_list.append(openid)
        atts_list.append(openid_user)
    else:
        fans_list.remove(openid)
        atts_list.remove(openid_user)

    sql_one = f"update user set fans = '{json.dumps(fans_list)}' where openid = '{openid_user}'"
    sql_two = f"update user set atts = '{json.dumps(atts_list)}' where openid = '{openid}'"
    sql_list = [sql_one,sql_two]
    DBUtil.execute_more(sql_list)
    return HttpSuccess(msg = '操作成功')



##发起对话
@checkLoginHandling
@checkParams(["persontwo_openid"])
def talk(request):
    json_data = json.loads(request.body)
    persontwo_openid = json_data.get("persontwo_openid")
    token = request.META.get("HTTP_X_TOKEN")
    openid = cache.get(token)
    select_sql = f"select * from  messageview where (personone_openid = '{openid}' and persontwo_openid = '{persontwo_openid}') or (personone_openid = '{persontwo_openid}' and persontwo_openid = '{openid}')"
    _ ,result =  DBUtil.execute_select(select_sql)
    if len(result) == 0:
        now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        insert_sql = f"insert into messageview(personone_openid,persontwo_openid,create_time)values('{openid}','{persontwo_openid}',{now})"
        _,id = DBUtil.execute_insert_or_update(insert_sql)
    else:
        id = result[0]['id']    
    return HttpSuccess(data = id)



    








